<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" style="width: 100%" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="shuju">
            <el-row
              class="position"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in shuju.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRightById(shuju.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="deleteRightById(shuju.row, item2.id)"
                      type="success"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      @close="deleteRightById(shuju.row, item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column
          type="index"
          label="#"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
          :resizable="false"
        ></el-table-column>
        <el-table-column label="操作" :resizable="false">
          <template v-slot="shuju">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showDialogVisible(shuju.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteRoleById(shuju.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(shuju.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 添加角色对话框是否显示
      addDialogVisible: false,
      // 添加角色数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色表单验证规则对象
      addRoleFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur',
          },
        ],
      },
      // 编辑角色对话框是否显示
      editDialogVisible: false,
      // 查询到的角色信息对象
      editRoleForm: {},
      // 修改表单验证规则对象
      editRoleFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur',
          },
        ],
      },
      // 分配权限对话框是否显示
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的节点ID值数组
      defKeys: [],
      // 当前即将分配权限的角色ID
      roleId: '',
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        // 提示错误
        return this.$message({
          duration: 2000,
          message: '获取角色列表失败！',
          type: 'error',
        })
      }
      this.roleList = res.data
    },
    // 监听添加角色对话框的关闭事件
    addDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 添加角色
    addRole() {
      this.$refs.addRoleFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 发起添加角色的网络请求
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message({
            duration: 2000,
            message: '添加角色失败！',
            type: 'error',
          })
        }
        this.$message({
          duration: 2000,
          message: '添加角色成功！',
          type: 'success',
        })
        // 隐藏对话框
        this.addDialogVisible = false
        // 重新渲染角色列表
        this.getRolesList()
      })
    },
    // 展示编辑角色的对话框
    async showDialogVisible(roleId) {
      const { data: res } = await this.$http.get(`roles/${roleId}`)
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '查询角色信息失败！',
          type: 'error',
        })
      }
      this.editRoleForm = res.data
      // 显示对话框
      this.editDialogVisible = true
    },
    // 监听编辑角色对话框的关闭事件
    editDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 编辑角色
    editRole() {
      this.$refs.editRoleFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 发起修改角色数据的网络请求
        const { data: res } = await this.$http.put(
          `roles/${this.editRoleForm.roleId}`,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message({
            duration: 2000,
            message: '修改角色失败！',
            type: 'error',
          })
        }
        // 提示修改成功
        this.$message({
          duration: 2000,
          message: '修改角色成功！',
          type: 'success',
        })
        // 隐藏对话框
        this.editDialogVisible = false
        // 重新渲染角色列表
        this.getRolesList()
      })
    },
    // 根据ID删除角色
    async deleteRoleById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //  如果用户确认删除，则返回值为 confirm
      //  如果用户取消删除，则返回值为 cancel
      if (confirmResult !== 'confirm') {
        return this.$message({
          duration: 2000,
          message: '取消删除角色！',
          type: 'info',
        })
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '删除角色失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '删除角色成功！',
        type: 'success',
      })
      // 重新渲染角色列表
      this.getRolesList()
    },
    // 根据ID删除权限
    async deleteRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //  如果用户确认删除，则返回值为 confirm
      //  如果用户取消删除，则返回值为 cancel
      if (confirmResult !== 'confirm') {
        return this.$message({
          duration: 2000,
          message: '取消删除权限！',
          type: 'info',
        })
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '删除权限失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '删除权限成功！',
        type: 'success',
      })
      // 赋值最新的权限，防止折叠
      role.children = res.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        // 提示错误
        return this.$message({
          duration: 2000,
          message: '获取权限数据失败！',
          type: 'error',
        })
      }
      // 把获取的数据保存到 data 中
      this.rightsList = res.data

      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的 id ，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr,
        }
      )
      if (res.meta.status !== 200) {
        // 提示错误
        return this.$message({
          duration: 2000,
          message: '分配权限失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '分配权限成功！',
        type: 'success',
      })
      this.getRolesList()
      this.setRightDialogVisible = false
    },
  },
}
</script>

<style scoped>
.position {
  margin-left: 50px;
}

.el-tag {
  margin: 8px;
  font-size: 13px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
